package cn.edu.zafu.bigdata.rwx;

import cn.hutool.system.SystemUtil;

import javax.swing.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class FileReadWrite {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的学号：");
        String studentId = sc.nextLine();
        System.out.println("请输入要保存的文本：");
        String content = sc.nextLine();
        sc.close();

        String fileName = "files"+ SystemUtil.getOsInfo().getFileSeparator()+studentId + ".txt";
        writeToFile(fileName, content);
        System.out.println("文件已保存到：" + fileName);
        readFromFile(fileName);
    }

    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("文本已经成功写入文件" + fileName);
        }
        catch (IOException e) {
            System.out.println("写入文件时出错：" + e.getMessage());
        }

    }
    public static void readFromFile(String fileName) {
        try{
            String content = new String(Files.readAllBytes(Paths.get(fileName)));
            System.out.println("文件内容为：" + content);
        }catch (IOException e){
            System.out.println("读取文件时出错：" + e.getMessage());
        }
    }
}
